# -*- coding:utf-8 -*-
from flask import Flask, request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao.unitDao import UnitDao

from . import app

CORS(app, supports_credentials=True)

'''单位用户表 zzh_unit API'''


@app.route('/unit-regist/<int:new_id>', methods=['POST'])
def unit_regist(new_id):
    if not request.json:
        abort(400)
    unit_info = {
        "unit_name": request.json['unit_name'],
        "unit_job": request.json['unit_job'],
        "unit_address": request.json['unit_address'],
        "unit_busness": request.json.get('unit_busness', ''),
        "unit_code": request.json.get('unit_code', ''),
        "unit_province": request.json.get('unit_province', ''),
        "unit_city": request.json.get('unit_city', ''),
        "unit_town": request.json.get('unit_town', '')
    }
    result = UnitDao().add_unit_info(new_id, unit_info)
    if result:
        return jsonify({"userInfo": unit_info, "message": {"code": 1, "info": "添加成功！"}})
    else:
        return jsonify({"message": {"code": 0, "info": "添加失败！"}})


@app.route('/update-unit/<int:unit_id>', methods=['POST'])
def update_unit(unit_id):
    if not request.json:
        abort(400)
    oldInfo = UnitDao().query_unit_by_id(unit_id)
    unit_info = {
        "unit_name": request.json.get('unit_name', oldInfo[1]),
        "unit_job": request.json.get('unit_job', oldInfo[2]),
        "unit_address": request.json.get('unit_address', oldInfo[3]),
        "unit_email": request.json.get('unit_email', oldInfo[4]),
        "unit_busness": request.json.get('unit_busness', oldInfo[5]),
        "unit_img": request.json.get('unit_img', oldInfo[6]),
        "unit_code": request.json.get('unit_code', oldInfo[7]),
        "unit_province": request.json.get('unit_province', oldInfo[8]),
        "unit_city": request.json.get('unit_city', oldInfo[9]),
        "unit_town": request.json.get('unit_town', oldInfo[10])
    }
    result = UnitDao().update_unit(unit_id, unit_info)

    return jsonify({"unitInfo": unit_info, "message": {"code": 1, "info": "更新成功！"}})


@app.route('/query-unit/<int:unit_id>', methods=['GET'])
def query_unit(unit_id):
    query_result = UnitDao().query_unit_info(unit_id)

    return jsonify({"unitInfo": query_result, "message": {"code": 1, "info": "OK"}})
